<template>
    <div style="width: 100%; height: 100%;">
        <div>
            <div class="align-stretch tree-panel">
                <org-tree style="height: 100%;" @node-click="handleNodeClick" />
            </div>
            <div class=" app-container" style="margin-left: 270px;">
                <div class="pageTitle">
                    <div class="pageBtn" style="padding-left: 0;">
                        <el-button size="small" type="primary" icon="el-icon-plus" @click="handleAdd()">添加</el-button>
                    </div>
                </div>

                <page-main style="margin: 10px 10px 0 0;">
                    <el-table ref="orderTable" v-loading="isLoading" class="actionTable" stripe :data="tableData"
                              header-cell-class-name="table-header" style="width: 100%;" border :row-class-name="tableRowClassName">
                        <el-table-column label="治超点名称" width="200" prop="name" />
                        <el-table-column label="治超点编号" width="150" prop="index_code" />
                        <el-table-column label="治超点类型" width="150" align="center">
                            <template slot-scope="scope">
                                <remote-dict-label dict="station_type" :value="scope.row.station_type" />
                            </template>
                        </el-table-column>

                        <el-table-column label="操作" width="150" align="center">
                            <template slot-scope="scope">
                                <el-button type="text" icon="el-icon-edit" style="margin-right: 10px;" @click="handleEdit(scope.row)">修改</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </page-main>
            </div>
        </div>

        <el-dialog :title="currentCrossing.isNew?'添加治超点':'修改治超点'" :visible.sync="detailVisible" width="800px">
            <div class="flex">
                <div style="width: 300px;">
                    <el-form ref="form" :model="currentCrossing" :rules="rules" label-width="120px" size="small">
                        <el-row>
                            <el-col :span="24">
                                <el-form-item label="所属组织机构">
                                    <span style="font-weight: bold;">{{ currentNode && currentNode.name }}</span>
                                </el-form-item>
                            </el-col>
                            <el-col :span="24">
                                <el-form-item label="治超点编号" prop="index_code">
                                    <el-input v-model="currentCrossing.index_code" placeholder="请输入路口编号" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="24">
                                <el-form-item label="治超点名称" prop="name">
                                    <el-input v-model="currentCrossing.name" placeholder="请输入路口名称" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="24">
                                <el-form-item label="治超点类型" prop="station_type">
                                    <remote-dict-select v-model="currentCrossing.station_type" :clearable="false" dict="station_type" />
                                </el-form-item>
                            </el-col>
                            <el-col :span="24">
                                <el-form-item label="卡口" prop="crossing_id">
                                    <el-select v-model="currentCrossing.crossing_id" clearable placeholder="请选择">
                                        <el-option v-for="(item,index) in crossingOptions" :key="index" :label="item.crossing_name" :value="item.crossing_id" />
                                    </el-select>
                                </el-form-item>
                            </el-col>
                            <el-col :span="24">
                                <el-form-item label="监控点" prop="camera_array">
                                    <el-select v-model="currentCrossing.camera_array" multiple collapse-tags clearable placeholder="请选择">
                                        <el-option v-for="(item,index) in monitoringOptions" :key="index" :label="item.cameraName" :value="item.camera_id" />
                                    </el-select>
                                </el-form-item>
                            </el-col>
                            <el-col :span="24">
                                <el-form-item label="经纬度" prop="latitude">
                                    <span v-if="markerPoint.lng">{{ markerPoint.lng+','+markerPoint.lat }}</span>
                                    <span v-else>点击地图进行标注→</span>
                                </el-form-item>
                            </el-col>
                        </el-row>
                    </el-form>
                </div>

                <div class="padding-left-sm flex-sub flex flex-direction" style="height: 350px;">
                    <map-point v-model="markerPoint" :init-center="initCenter" />
                </div>
            </div>

            <div slot="footer" class="dialog-footer">
                <el-button size="small" @click="detailVisible = false">取 消</el-button>
                <el-button size="small" :loading="isLoading" type="primary" @click="handleSubmit">确 定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import moment from 'moment';
import OrgTree from './OrgTree';
import DictSelect from '@/modules/components/DictSelect';
import RemoteDictSelect from '@/modules/components/DictSelect/RemoteDictSelect';
import {dictFilter} from '@/modules/components/DictSelect/dict-data';
import MapPoint from './MapPoint';
import RemoteDictLabel from '@/modules/components/DictSelect/RemoteDictLabel';

import {
    GetCrossingNameConfiguration,
    AddCrossingNameConfiguration,
    UpdateCrossingNameConfiguration,
    InquiryOrganizationCrossing,
    OrganizationMonitoring,
    GetOvershootQuery
} from '@/api/resourceManageApi';

export default {
    name: 'overload-station-config',
    components: {
        OrgTree, RemoteDictSelect, DictSelect, MapPoint, RemoteDictLabel
    },
    filters: {
        formatStationType(value) {
            return dictFilter(value, 'dict_StationType');
        }
    },
    props: {},
    data() {
        return {
            markerPoint: {},
            initCenter: {},
            isLoading: false,
            tableData: [],
            detailVisible: false,
            currentCrossing: {},
            rules: {
                name: [
                    { required: true, message: '名称不能为空', trigger: 'blur' }
                ],
                index_code: [
                    { required: true, message: '编号不能为空', trigger: 'blur' }
                ],
                station_type: [
                    { required: true, message: '类型不能为空', trigger: 'change' }
                ],
                crossing_id: [
                    { required: true, message: '卡口不能为空', trigger: 'change' }
                ],
                latitude: [
                    { required: true, message: '经纬度必须设置', trigger: 'change' }
                ]
            },
            monitoringOptions: [],
            crossingOptions: [],
            currentNode: null
        };
    },
    computed: {

    },
    watch: {
        markerPoint: {
            deep: true,
            handler(val) {
                this.currentCrossing.latitude = val.lat;
                this.currentCrossing.longitude = val.lng;
                this.$refs['form'] && this.$refs['form'].clearValidate('latitude');
            }
        }
    },
    created() {

    },
    mounted() {
        this.loadRemoteData();
    },
    methods: {
        moment,
        tableRowClassName({row, rowIndex}) {
            if (this.detailVisible && this.currentCrossing.id == row.id) {
                return 'selected-row';
            }
            return '';
        },
        handleNodeClick(data) {
            this.currentNode = data;
            this.loadRemoteData();
        },
        loadRemoteData() {
            if (!this.currentNode) {
                return;
            }

            this.isLoading = true;
            let params = {control_unit_id: this.currentNode.control_unit_id};
            GetCrossingNameConfiguration(params).then(res => {
                this.isLoading = false;
                this.tableData = res.res.CrossingNameConfiguration;
            }).catch(err => {
                this.isLoading = false;
                console.log(err);
            });
        },
        handleAdd() {

            if (!this.currentNode) {
                this.$message.warning('请先选择组织');
                return;
            }

            this.currentCrossing = {
                isNew: true,
                latitude: '',
                longitude: '',
                camera_array: [],
                control_unit_id: this.currentNode ? this.currentNode.control_unit_id : undefined
            };
            this.loadCrossingOptions();
            this.loadMonitoringOptions();
            this.markerPoint = {};
            this.initCenter = {...this.markerPoint};
            this.detailVisible = true;
            this.$nextTick(() => {
                this.$refs['form'] && this.$refs['form'].clearValidate();
            });
        },

        handleEdit(item) {

            this.loadCrossingOptions();
            this.loadMonitoringOptions();

            this.isLoading = true;
            GetOvershootQuery({
                id: item.id
            }).then(res => {
                this.isLoading = false;

                this.currentCrossing = res.res.GetOvershootQuery && res.res.GetOvershootQuery[0];
                this.currentCrossing.id = item.id;
                this.$set(this.currentCrossing, 'camera_array', (this.currentCrossing.camera_ids) ? this.currentCrossing.camera_ids.split(',').map(Number) : []);
                this.currentCrossing.station_type = this.currentCrossing.station_type.toString();
                this.markerPoint = {lat: this.currentCrossing.latitude, lng: this.currentCrossing.longitude};
                this.initCenter = {...this.markerPoint};
                this.detailVisible = true;
                this.$nextTick(() => {
                    this.$refs['form'] && this.$refs['form'].clearValidate();
                });
            }).catch(err => {
                this.isLoading = false;
                console.log(err);
            });

        },

        handleSubmit() {
            if (this.clickTooFast()) return;
            this.$refs['form'].validate(valid => {
                if (valid) {
                    this.isLoading = true;

                    this.currentCrossing.camera_ids = this.currentCrossing.camera_array ? this.currentCrossing.camera_array.join(',') : '';

                    if (this.currentCrossing.isNew) {
                        AddCrossingNameConfiguration(this.currentCrossing).then(res => {
                            this.$message.success('添加成功');
                            this.loadRemoteData();
                            this.detailVisible = false;
                            this.isLoading = false;
                        }).catch(err => {
                            this.isLoading = false;
                            console.log(err);
                        });
                    } else {
                        UpdateCrossingNameConfiguration(this.currentCrossing).then(res => {
                            this.$message.success('修改成功');
                            this.loadRemoteData();
                            this.detailVisible = false;
                            this.isLoading = false;
                        }).catch(err => {
                            this.isLoading = false;
                            console.log(err);
                        });
                    }
                }
            });
        },

        loadCrossingOptions() {
            this.crossingOptions = [];
            InquiryOrganizationCrossing({
                control_unit_id: this.currentNode.control_unit_id
            }).then(res => {
                this.crossingOptions = res.res.InquiryOrganizationCrossing;
            }).catch(err => {
                console.log(err);
            });
        },

        loadMonitoringOptions() {
            this.monitoringOptions = [];
            OrganizationMonitoring({
                control_unit_id: this.currentNode.control_unit_id
            }).then(res => {
                this.monitoringOptions = res.res.camera;
            }).catch(err => {
                console.log(err);
            });
        }

    }
};
</script>

<style scoped>

.table-header {
    background-color: #f8f8f8 !important;
}
/deep/
.el-table td {
    padding: 5px 0 !important;
}
/deep/
.el-button--text {
    padding: 5px 0;
}
/deep/
.el-dialog__body {
    padding: 10px 20px;
}
/deep/
.el-dialog__header {
    padding: 20px 20px 10px;
    border-bottom: 1px solid #dcdfe6;
}
</style>

<style lang="scss" scoped>

.table-header {
    background-color: #f8f8f8 !important;
}
.el-table ::v-deep td {
    padding: 5px 0 !important;
}
.tree-panel {
    margin-left: var(--real-sidebar-width);
    height: calc(100% - 120px);
    position: fixed;
    z-index: 100;
    left: 0;
    width: 260px;
    padding-left: 5px;
    padding-top: 5px;
    background: #fbfbfb;
    border: 1px solid #e5e5e5;
    margin-right: 10px;
}
</style>
